package cn.akwangl.concurrency.web.init;

import cn.akwangl.concurrency.web.common.OrderConstant;
import cn.akwangl.concurrency.web.model.items.pojo.ItemsSpecEntity;
import cn.akwangl.concurrency.web.model.items.service.ItemsSpecService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 商品库存Redis 缓存.
 *
 * @author 阿坤同学
 * @date 2022/11/27 16:32
 */
@Slf4j
@Component
public class RedisSkuCache implements ApplicationRunner {

    private RedissonClient redissonClient;

    private ItemsSpecService itemsSpecService;

    @Autowired
    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Autowired
    public void setItemsSpecService(ItemsSpecService itemsSpecService) {
        this.itemsSpecService = itemsSpecService;
    }

    @Override
    public void run(ApplicationArguments args) {
        StringBuilder sb = new StringBuilder();

        long current = 1;
        long size = 500;
        Page<ItemsSpecEntity> page;
        do {
            page = itemsSpecService.page(new Page(current, size));

            page.getRecords().forEach(itemsSpecEntity -> {
                String itemsSpecId = itemsSpecEntity.getId();
                Integer stock = itemsSpecEntity.getStock();

                String redisKye = sb.append(OrderConstant.ITEMS_STOCK).append(itemsSpecId).toString();
                Integer redisValue = stock;
                redissonClient.getBucket(redisKye).set(redisValue);
                sb.setLength(0);
            });
            current++;
        } while (page.hasNext());
        log.info("商品库存同步成功");
    }
}
